import axios from 'axios'

const CURRT_CITY = 'current_city'

//
export function setCity(city) {
  localStorage.setItem(CURRT_CITY, JSON.stringify(city))
}

export function getCurrentCity(callback) {
  return new Promise((resolve, reject) => {
    const currentCity = JSON.parse(localStorage.getItem('current_city'))
    if (currentCity) {
      resolve(currentCity)
      callback && callback(currentCity)
    } else {
      const myCity = new window.BMap.LocalCity()
      myCity.get(async (result) => {
        // const cityName = result.name
        //   console.log(result, 99)
        const res = await axios.get(
          `http://localhost:8080/area/info?name=${result.name}`
        )
        console.log(res)
        const { status, body } = res.data
        if (status === 200) {
          // localStorage.setItem('current_city', JSON.stringify(body))
          setCity(body)
          resolve(body)
          callback && callback(body)
        } else {
          reject('获取城市信息失败')
          callback && callback('获取城市信息失败')
        }
      })
    }
  })
}
